import Footer from '@/components/Footer';
import {register} from '@/services/ant-design-pro/api';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import { message, Tabs } from 'antd';
import React, { useState } from 'react';
import {history, Link, useModel} from 'umi';
import styles from './index.less';
const Register: React.FC = () => {
  const [userLoginState] = useState<API.LoginResult>({
    code: "",
    data: {
      avatarUrl: "",
      createTime: "",
      email: "",
      gender: 0,
      id: 0,
      isDelete: "",
      password: "",
      phone: "",
      status: "",
      updateTime: "",
      userAccount: "",
      userRole: "",
      username: ""
    },
    msg: ""

  });
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({
        ...s,
        currentUser: userInfo,
      }));
    }
  };
  const handleSubmit = async (values: API.RegisterParams) => {
    try {
      if(values.password !== values.checkPassword){
        throw new Error("两次输入密码不一致！");
      }
      // 注册
      const result = await register({
        ...values,
      });
      console.log(`1111111111111`)
      console.log(`result.data : ${result.data}`)
      if (result.data > 0) {
        const defaultLoginSuccessMessage = '注册成功！';
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as {
          redirect: string;
        };
        console.log(`histoty.localtion ${history.location}`);
        console.log(`redirect ${redirect}`);
        console.log(`history ${history}`);
        history.push(redirect || '/');
        return;
      }else{
        throw new Error(`${result.msg}`);
      }
    } catch (error) {
      // @ts-ignore
      message.error(error.message);
    }
  };
  // @ts-ignore
  const { status, type: loginType } = userLoginState;
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src="/logo.svg" />}
          title="Ant Design"
          subTitle={'Ant Design 是西湖区最具影响力的 Web 设计规范'}
          initialValues={{
            autoLogin: true,
          }}

          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane key="account" tab={'账户密码注册'} />
          </Tabs>


          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'用户名'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                  {
                    min: 8,
                    type: 'string',
                    message: '密码不能小于8位'
                  }
                ]}
              />

              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请在次输入密码'}
                rules={[
                  {
                    required: true,
                    message: '确认密码必须要填！',
                  },
                  {
                    min: 8,
                    type: 'string',
                    message: '密码不能小于8位'
                  }
                ]}
              />
            </>
          )}
          <div>
            <Link to={"/user/login"}>返回登录页面</Link>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Register;
